package com.tonghe.runner;

import com.tonghe.constants.SystemConstants;
import com.tonghe.domain.entity.Article;
import com.tonghe.mapper.ArticleMapper;
import com.tonghe.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Date:2022/5/9- 05- 09- 15:27
 **/
@Component
public class ViewCountRunner implements CommandLineRunner {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ArticleMapper articleMapper;

    /**
    * @description: 在应用启动时初始化缓存存入浏览量信息
    * @author: TongHe
    * @date: 2022/8/14 19:10
    */
    @Override
    public void run(String... args) throws Exception {

        // 1、查询博客信息
        List<Article> articleList = articleMapper.selectList(null);

        // 2、封装成map对象（id，viewCount）直接调用API
        Map<String, Integer> map = articleList.stream()
                .collect(Collectors.toMap(article -> article.getId().toString()
                        , article -> article.getViewCount().intValue())); // 每个泛型都值得推敲
        // 3、存储到redis中
        redisCache.setCacheMap(SystemConstants.REDIS_VIEW_COUNT, map);
    }
}
